import { ActionContext, Module } from "vuex";
import { GlobalDataProps,actionWrapper } from ".";
import axios,{AxiosRequestConfig} from "axios";
import type { RespData } from "./respTypes";
export interface UserProps {
  isLogin: boolean;
  data?: UserDataProps;
  token?: string;
}
export interface UserDataProps{
  username?: string;
  id?: string;
  phoneNumber?: string;
  nickName?: string;
  description?: string;
  updateAt?: string;
  createAt?: string;
  iat?: number;
  exp?: number;
  picture?: string;
  gender?: number;
}


const user: Module<UserProps, GlobalDataProps> = {
  state: {
    isLogin: false,
    data: {},
    token: localStorage.getItem("token") || "",
  },
  mutations: {
    login(state, rawData: RespData<{token: string}>) {
      const { data } = rawData;
      console.log("login accessToken: ", rawData.data);
      state.token = data.token;
      localStorage.setItem("token", data.token);
      //设置全局请求头
      axios.defaults.headers.common.Authorization = `Bearer ${data.token}`;
    },
    fetchCurrentUser(state, rawData: RespData<UserDataProps>) {
      state.isLogin = true;
      console.log('fetchCurrentUser',rawData.data);
      state.data = {...rawData.data};
    },
    logout(state) {
      state.isLogin = false;
      state.token = "";
      state.data = {};
      localStorage.removeItem("token");
      delete axios.defaults.headers.common.Authorization;
    },
  },
  actions: {
    // login({ commit }, payload) {
    //   console.log("user login payload: ", payload);
    //   return axios
    //     .post("/users/loginByPhoneNumber", payload)
    //     .then((rawData) => {
    //       commit("login", rawData);
    //     });
    // },
    login: actionWrapper("/users/loginByPhoneNumber", "login", {method: 'post'}),
    // fetchCurrentUser({ commit, }) {
    //   return axios.get("/users/getUserInfo").then((rawData) => {
    //     commit("fetchCurrentUser", rawData.data);
    //   });
    // },
    fetchCurrentUser: actionWrapper("/users/getUserInfo", "fetchCurrentUser"),
    loginAndFetch({ dispatch }, loginData) {
      return dispatch("login", loginData).then(() => {
        return dispatch("fetchCurrentUser");
      }); 
    }
  },
};

export default user;
